package com.ruoyi.setlanguages.service;

import com.google.api.services.youtube.YouTube;
import com.ruoyi.setlanguages.io.ChannelInfo;
import com.ruoyi.setlanguages.io.VideoInfo;
import com.ruoyi.setlanguages.until.YouTubeAuth;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class YouTubeChannelManager {
    private YouTubeManager youTubeManager;
    private Scanner scanner;
    private String currentCredentialsPath;

    public YouTubeChannelManager(YouTubeManager youTubeManager) {
        this.youTubeManager = youTubeManager;
        this.scanner = new Scanner(System.in);
        this.currentCredentialsPath = YouTubeAuth.getCredentialsFilePath();
    }

    public void run() {
        System.out.println("=== YouTube频道管理器 ===");
        System.out.println("当前凭证文件: " + currentCredentialsPath);

        while (true) {
            showMenu();

            try {
                String input = scanner.nextLine();

                if (input.isEmpty()) continue;

                int choice = Integer.parseInt(input);
                System.out.println("\n请选择操作:");
                System.out.println("1. 查看我的频道");
                System.out.println("2. 查看频道视频");
                System.out.println("3. 编辑视频标题");
                System.out.println("4. 为视频添加多语言标题");
                System.out.println("5. 为视频添加单个语言标题");
                System.out.println("6. 查看视频的多语言标题");
                System.out.println("7. 查看支持的语言");
                System.out.println("8. 切换凭证文件");
                System.out.println("9. 清除当前凭证");
                System.out.println("0. 退出");
                switch (choice) {
                    case 1:
                        //查看我的频道
                        listMyChannels();
                        break;
                    case 2:

                        //查看频道视频
                        listChannelVideos();
                        break;
                    case 3:
                        //编辑视频标题
                        editVideoTitle();
                        break;
                    case 4:
                        //为视频添加多语言标题
                        addMultiLanguageTitles();
                        break;
                    case 5:
                        //为视频添加单个语言标题
                        addSingleLanguageTitle();
                        break;
                    case 6:
                        //查看视频的多语言标题
                        viewVideoLocalizations();
                        break;
                    case 7:
                        //查看支持的语言
                        showSupportedLanguages();
                        break;
                    case 8:
                        //切换凭证文件
                        changeCredentials();
                        break;
                    case 9:
                        //清除当前凭证
                        clearCredentials();
                        break;
                    case 0:
                        System.out.println("再见!");
                        return;
                    default:
                        System.out.println("无效选择!");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入数字!");
            } catch (Exception e) {
                System.out.println("错误: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private void showMenu() {
        System.out.println("\n请选择操作:");
        System.out.println("1. 查看我的频道");
        System.out.println("2. 查看频道视频");
        System.out.println("3. 编辑视频标题");
        System.out.println("4. 为视频添加多语言标题");
        System.out.println("5. 为视频添加单个语言标题");
        System.out.println("6. 查看视频的多语言标题");
        System.out.println("7. 查看支持的语言");
        System.out.println("8. 切换凭证文件");
        System.out.println("9. 清除当前凭证");
        System.out.println("0. 退出");
        System.out.print("请输入选择: ");
    }

    private void listMyChannels() throws IOException {
        System.out.println("\n=== 我的频道 ===");
        List<ChannelInfo> channels = youTubeManager.getMyChannels();

        if (channels.isEmpty()) {
            System.out.println("未找到频道");
            return;
        }

        for (int i = 0; i < channels.size(); i++) {
            System.out.println("[" + (i + 1) + "] " + channels.get(i));
        }
    }

    private void listChannelVideos() throws IOException {
        System.out.print("请输入频道ID: ");
        String channelId = scanner.nextLine().trim();

        if (channelId.isEmpty()) {
            System.out.println("频道ID不能为空");
            return;
        }

        System.out.println("\n=== 频道视频 ===");
        List<VideoInfo> videos = youTubeManager.getChannelVideos(channelId);

        if (videos.isEmpty()) {
            System.out.println("未找到视频或频道不存在");
            return;
        }

        System.out.println("找到 " + videos.size() + " 个视频:");
        for (int i = 0; i < videos.size(); i++) {
            VideoInfo video = videos.get(i);
            System.out.println("[" + (i + 1) + "] " + video.getTitle());
            System.out.println("    ID: " + video.getId());
            System.out.println("    发布时间: " + video.getPublishedAt());
            System.out.println();
        }
    }

    private void editVideoTitle() throws IOException {
        System.out.print("请输入视频ID: ");
        String videoId = scanner.nextLine().trim();

        if (videoId.isEmpty()) {
            System.out.println("视频ID不能为空");
            return;
        }

        System.out.print("请输入新标题: ");
        String newTitle = scanner.nextLine().trim();

        if (newTitle.isEmpty()) {
            System.out.println("标题不能为空");
            return;
        }

        youTubeManager.updateVideoTitle(videoId, newTitle);
    }

    private void addMultiLanguageTitles() throws IOException {
        System.out.print("请输入视频ID: ");
        String videoId = scanner.nextLine().trim();

        if (videoId.isEmpty()) {
            System.out.println("视频ID不能为空");
            return;
        }

        Map<String, String> languageTitles = new HashMap<>();
        Map<String, String> supportedLanguages = YouTubeManager.getSupportedLanguages();

        System.out.println("\n支持的语言:");
        for (Map.Entry<String, String> entry : supportedLanguages.entrySet()) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }

        System.out.println("\n请输入多语言标题 (输入 'done' 结束):");
        while (true) {
            System.out.print("语言代码 (如: ja): ");
            String langCode = scanner.nextLine().trim();

            if ("done".equalsIgnoreCase(langCode)) {
                break;
            }

            if (!YouTubeManager.isLanguageSupported(langCode)) {
                System.out.println("不支持的语言代码! 请输入正确的语言代码。");
                continue;
            }

            System.out.print(supportedLanguages.get(langCode) + "标题: ");
            String title = scanner.nextLine().trim();

            if (title.isEmpty()) {
                System.out.println("标题不能为空，跳过此语言。");
                continue;
            }

            languageTitles.put(langCode, title);
            System.out.println("已添加 " + supportedLanguages.get(langCode) + " 标题");
        }

        if (!languageTitles.isEmpty()) {
            youTubeManager.addMultiLanguageTitle(videoId, languageTitles);
            System.out.println("多语言标题添加成功!");
        } else {
            System.out.println("未添加任何语言标题");
        }
    }

    private void addSingleLanguageTitle() throws IOException {
        System.out.print("请输入视频ID: ");
        String videoId = scanner.nextLine().trim();

        if (videoId.isEmpty()) {
            System.out.println("视频ID不能为空");
            return;
        }

        Map<String, String> supportedLanguages = YouTubeManager.getSupportedLanguages();
        System.out.println("\n支持的语言:");
        for (Map.Entry<String, String> entry : supportedLanguages.entrySet()) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }

        System.out.print("请输入语言代码 (如: ja): ");
        String langCode = scanner.nextLine().trim();

        if (!YouTubeManager.isLanguageSupported(langCode)) {
            System.out.println("不支持的语言代码!");
            return;
        }

        System.out.print("请输入" + supportedLanguages.get(langCode) + "标题: ");
        String title = scanner.nextLine().trim();

        if (title.isEmpty()) {
            System.out.println("标题不能为空");
            return;
        }

        youTubeManager.addSingleLanguageTitle(videoId, langCode, title);
        System.out.println(supportedLanguages.get(langCode) + "标题添加成功!");
    }

    private void viewVideoLocalizations() throws IOException {
        System.out.print("请输入视频ID: ");
        String videoId = scanner.nextLine().trim();

        if (videoId.isEmpty()) {
            System.out.println("视频ID不能为空");
            return;
        }

        System.out.println("\n=== 视频多语言标题 ===");
        Map<String, String> localizations = youTubeManager.getVideoLocalizations(videoId);

        if (localizations.isEmpty()) {
            System.out.println("该视频没有设置多语言标题");
            return;
        }

        Map<String, String> supportedLanguages = YouTubeManager.getSupportedLanguages();
        System.out.println("当前设置的多语言标题:");
        for (Map.Entry<String, String> entry : localizations.entrySet()) {
            String languageName = supportedLanguages.getOrDefault(entry.getKey(), entry.getKey());
            System.out.println("  " + languageName + " (" + entry.getKey() + "): " + entry.getValue());
        }
    }

    private void showSupportedLanguages() {
        System.out.println("\n=== 支持的语言 ===");
        Map<String, String> languages = YouTubeManager.getSupportedLanguages();
        System.out.println("语言代码 - 语言名称");
        System.out.println("-------------------");
        for (Map.Entry<String, String> entry : languages.entrySet()) {
            System.out.println(entry.getKey() + " - " + entry.getValue());
        }
        System.out.println("\n使用示例:");
        System.out.println("  ja - 日语标题");
        System.out.println("  en - 英语标题");
        System.out.println("  ko - 韩语标题");
    }

    private void changeCredentials() {
        System.out.println("\n当前凭证文件: " + currentCredentialsPath);
        System.out.print("请输入新的凭证文件路径: ");
        String newPath = scanner.nextLine().trim();

        if (newPath.isEmpty()) {
            System.out.println("路径不能为空");
            return;
        }

        try {
            // 清除当前凭证
            YouTubeAuth.clearCredentials();

            // 使用新路径创建服务
            YouTube newYouTubeService = YouTubeAuth.getYouTubeService();
            this.youTubeManager = new YouTubeManager(newYouTubeService);
            this.currentCredentialsPath = newPath;

            System.out.println("凭证文件已切换到: " + newPath);
            System.out.println("请重新进行认证...");

        } catch (Exception e) {
            System.out.println("切换凭证文件失败: " + e.getMessage());
            // 尝试恢复原来的服务
            try {
                YouTube originalService = YouTubeAuth.getYouTubeService();
                this.youTubeManager = new YouTubeManager(originalService);
            } catch (Exception ex) {
                System.out.println("恢复原服务失败: " + ex.getMessage());
            }
        }
    }

    private void clearCredentials() throws IOException {
        System.out.print("确定要清除当前凭证吗? (y/N): ");
        String confirm = scanner.nextLine().trim();
        if ("y".equalsIgnoreCase(confirm)) {
            YouTubeAuth.clearCredentials();
            System.out.println("凭证已清除，下次运行程序时需要重新认证");

            // 重新初始化服务以触发新的认证流程
            try {
                YouTube newYouTubeService = YouTubeAuth.getYouTubeService();
                this.youTubeManager = new YouTubeManager(newYouTubeService);
                System.out.println("已重新初始化YouTube服务");
            } catch (Exception e) {
                System.out.println("重新初始化服务失败: " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("初始化YouTube服务...");
            System.out.println("凭证文件路径: " + YouTubeAuth.getCredentialsFilePath());

            YouTube youtubeService = YouTubeAuth.getYouTubeService();
            YouTubeManager manager = new YouTubeManager(youtubeService);
            YouTubeChannelManager app = new YouTubeChannelManager(manager);
            app.run();

        } catch (Exception e) {
            System.err.println("程序运行错误: " + e.getMessage());
            System.err.println("请检查:");
            System.err.println("1. 凭证文件路径是否正确: " + YouTubeAuth.getCredentialsFilePath());
            System.err.println("2. 凭证文件格式是否正确");
            System.err.println("3. 网络连接是否正常");
            e.printStackTrace();
        }
    }
}